/**
 * Project: complex.quartz
 * 
 * File Created at 2010-6-29
 * $Id$
 * 
 * Copyright 2008 Alibaba.com Croporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Alibaba Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Alibaba.com.
 */
package com.complex.quartz;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.TriggerUtils;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.calendar.AnnualCalendar;

/**
 * @description:使用Calendar来排除一些特定时间
 * @author gaoliang
 * @date 2010-6-29
 * @version 1.0
 */
public class CalendarExample {
    public static void main(String[] args) {
        SchedulerFactory sf = new StdSchedulerFactory();

        Scheduler scheduler = null;
        try {
            scheduler = sf.getScheduler();
        } catch (SchedulerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //法定节日是以每年为周期的，所以使用AnnualCalendar

        AnnualCalendar holidays = new AnnualCalendar();

        //五一劳动节

        Calendar laborDay = new GregorianCalendar();

        laborDay.add(Calendar.MONTH, 5);

        laborDay.add(Calendar.DATE, 1);

        //排除的日期，如果设置为false则为包含

        //国庆节
        holidays.setDayExcluded(laborDay, true);

        Calendar nationalDay = new GregorianCalendar();

        nationalDay.add(Calendar.MONTH, 10);

        nationalDay.add(Calendar.DATE, 1);
        //排除该日期
        holidays.setDayExcluded(nationalDay, true);

        //向Scheduler注册日历
        try {
            scheduler.addCalendar("holidays", holidays, false, false);
        } catch (SchedulerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //4月1号 上午10点
        Date runDate = TriggerUtils.getDateOf(0, 0, 10, 1, 4);

        JobDetail job = new JobDetail("job1", "group1", SimpleJob.class);

        SimpleTrigger trigger = new SimpleTrigger("trigger1", "group1",

        runDate,

        null,

        SimpleTrigger.REPEAT_INDEFINITELY,

        60L * 60L * 1000L);

        //让Trigger应用指定的日历规则
        trigger.setCalendarName("holidays");

        try {
            scheduler.scheduleJob(job, trigger);
            scheduler.start();
        } catch (SchedulerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //实际应用中主线程不能停止，否则Scheduler得不到执行，此处从略

    }
}
